package com.example.config.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.example.entity.TUser;
import com.example.mapper.TUserMapper;
import com.example.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;


@Slf4j
public class ReadUserListener implements ReadListener<TUser> {
    public static final Integer BATCH_COUNT = 100;
    public List<TUser> cachedUserDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private TUserMapper tUserMapper;

    public ReadUserListener() {
//        tUserMapper = new TUserMapper();
    }

    public ReadUserListener(TUserMapper tUserMapper) {
        this.tUserMapper = tUserMapper;
    }

    @Override
    public void invoke(TUser tUser, AnalysisContext analysisContext) {
        log.info("解析到一条数据{}", JSONUtils.toJSON(tUser));
        cachedUserDataList.add(tUser);
//        如果数据量已达标，则将缓存中的数据写入到数据库中
        if (cachedUserDataList.size() > BATCH_COUNT) {
            saveData();
//            存储并清理缓存中的数据
            cachedUserDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
//        解析完后需要再调用一次，原因在于：如果有103条数据，invoke时前100条写入了，但剩了3条还未写入，需要写进去
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedUserDataList.size());
        tUserMapper.saveUser(cachedUserDataList);
        log.info("存储数据库成功！");
    }
}
